package com.sanri.tools.modules.core.controller;

import com.sanri.tools.modules.core.exception.ToolException;
import com.sanri.tools.modules.core.service.connect.ActiveConnectManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 活动连接管理
 */
@RestController
@RequestMapping("/connect/active")
@Validated
public class ActiveConnectController {
    @Autowired(required = false)
    private List<ActiveConnectManage> activeConnectManages = new ArrayList<>();

    /**
     * 活动连接列表
     * @param module 模块名
     * @return
     */
    @GetMapping("/connects")
    public Set<String> activeConnects(@NotBlank String module){
        ActiveConnectManage activeConnectManage = choseActiveConnectManage(module);
        return activeConnectManage.activeConnects();
    }

    /**
     * 杀掉连接
     * @param module 模块名
     * @param id 连接ID
     * @return
     */
    @PostMapping("/kill")
    public boolean kill(@NotBlank String module, @NotBlank String id){
        ActiveConnectManage activeConnectManage = choseActiveConnectManage(module);
        return activeConnectManage.kill(id);
    }

    /**
     * 重连
     * @param module 模块名
     * @param id 连接 ID
     */
    @PostMapping("/reconnect")
    public void reconnect(@NotBlank String module, @NotBlank String id) throws Exception {
        ActiveConnectManage activeConnectManage = choseActiveConnectManage(module);
        activeConnectManage.reconnect(id);
    }

    private ActiveConnectManage choseActiveConnectManage(@NotBlank String module) {
        for (ActiveConnectManage activeConnectManage : activeConnectManages) {
            if (module.equals(activeConnectManage.module())){
                return activeConnectManage;
            }
        }
        throw new ToolException("当前模块 " + module + " 不支持活动连接管理");
    }
}
